package com.badibadi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.amap.api.location.AMapLocation;
import com.badibadi.activity.BaseActivity.ViewFragmentHolder;
import com.badibadi.activity.RigionPictureActivity.RigionPictureFragment01.RigionPicture01Adapter;
import com.badibadi.adapter.ClubOverviewZuixinAdapter_1;
import com.badibadi.adapter.Popwindows_Adapter;
import com.badibadi.fragment.BaseFragment;
import com.badibadi.fragment.ClubOverview0Fragmente;
import com.badibadi.fragment.MyClubFragment0.getFragmentData;
import com.badibadi.infos.Area_More_Clubs_Model;
import com.badibadi.infos.Area_More_Imgs_Model;
import com.badibadi.infos.ClubModel;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.Results;
import com.badibadi.infos.photoImgs_Model;
import com.badibadi.mytools.AMapLocationUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.TabHostUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.AMapLocationUtils.getAMapLocation;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.id;
import com.badibadi.uniclubber.R.string;
import com.libjph.util.JsonUtil;
import com.miloisbadboy.view.PullToRefreshView;
import com.miloisbadboy.view.PullToRefreshView.OnFooterRefreshListener;
import com.miloisbadboy.view.PullToRefreshView.OnHeaderRefreshListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TabHost;
import android.widget.TextView;

public class ClubRigionListActivity extends ClubListActivity {
	private String areaid;
	private TextView club_overview_title;
	private ClubRigionListFragment clubRigionListFragment;
	private Bundle bun;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					club_overview_title.setText(msg.getData()
							.getString("tital"));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2:
				Utils.ExitPrgress(ClubRigionListActivity.this);
				try {
					Utils.showMessage(ClubRigionListActivity.this,
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				Utils.ExitPrgress(ClubRigionListActivity.this);
				break;
			case 4:
				Utils.ExitPrgress(ClubRigionListActivity.this);
				try {
					Utils.showMessage(ClubRigionListActivity.this,
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		init();
		InitializeFragment("1");
//		   
	}

	private void init() {
		try {
			areaid = getIntent().getStringExtra("areaid");
		} catch (Exception e) {
			   
		}

		club_overview_title = (TextView) findViewById(R.id.club_overview_title);
		this.findViewById(R.id.club_overview_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						clubRigionListFragment.Set();

					}
				});
	}

	@Override
	protected void initTabHost(int stringTab3) {
		mTabHost = (TabHost) findViewById(R.id.club_list_tabhost);
		mTabHost.setup();
		mTabHost.addTab(mTabHost
				.newTabSpec("club_list one")
				.setIndicator(getResources().getString(R.string.Newest),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab1));
		mTabHost.addTab(mTabHost
				.newTabSpec("club_list two")
				.setIndicator(getResources().getString(R.string.Hottest),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab2));
		mTabHost.addTab(mTabHost
				.newTabSpec("club_list three")
				.setIndicator(getResources().getString(R.string.All),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab3));
		TabHostUtils.SetTabHost(this, mTabHost);
		mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				// Toast.makeText(getApplicationContext(),
				// "" + mTabHost.getCurrentTab(), 0).show();
				switch (mTabHost.getCurrentTab()) {
				case 0:
					InitializeFragment("1");
					break;
				case 1:
					InitializeFragment("2");
					break;
				case 2:
					InitializeFragment("3");
					break;
				default:
					InitializeFragment("1");
					break;
				}
			}
		});
	}

	/**
	 * 初始化fragment
	 */
	protected void InitializeFragment(String type) {
		ViewFragmentHolder viewHolder = new ViewFragmentHolder();
		clubRigionListFragment = new ClubRigionListFragment();
		bun = new Bundle();
		bun.putString("type", type);
		clubRigionListFragment.setArguments(bun);
		viewHolder.transaction.replace(R.id.club_overview_layout,
				clubRigionListFragment);
		viewHolder.transaction.commit();
	}

	@SuppressLint("ValidFragment")
	public class ClubRigionListFragment extends BaseFragment implements
			OnHeaderRefreshListener, OnFooterRefreshListener {
		private boolean popwindow = false;
		// private XGridView gv;
		private PullToRefreshView mPullToRefreshView;
		private GridView gv;
		private int Page;
		private List<ClubModel> clubModels, clubs;
		private String type_temp;
		private Area_More_Clubs_Model area_More_Clubs_Model;
		private ClubOverviewZuixinAdapter_1 clubOverviewZuixinAdapter_1;
		private boolean judge;
		private Message message;
		private Bundle bundle;
		private PopupWindow popup = null;
		private ListView type_list;
		private Popwindows_Adapter popwindows_Adapter;
		private List<ClueTypeModel> clueTypeModels;
		private LinearLayout fragment_club_overview0_btn_type_xgridview;
		// private AutoCompleteTextView index_autocomplete_txt_view_xgridview;
		// private ImageView xgridview_uppic_settings;
		private LinearLayout xgridview_search;
		private TextView xgridview_TheKeyword;
		private LinearLayout xgridview_keyword_kuang;
		private boolean isReturnUp = true;// 按返回键是否回退关键字
		private boolean isSouSuo1 = true;
		private boolean isSouSuo2 = true;
		private String searchName = null;
		private String tid = "0";// 活动类型id
		private Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				try {
					switch (msg.what) {
					case 1:
						Utils.ExitPrgress(getActivity());
						try {
							Utils.showMessage(getActivity(), getResources()
									.getString(R.string.l_net_error));
							mPullToRefreshView.onFooterRefreshComplete();
							mPullToRefreshView.onHeaderRefreshComplete();
							if (mPullToRefreshView.getVisibility() == 0
									&& clubModels.isEmpty()) {
								mPullToRefreshView.setVisibility(View.GONE);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}

						break;
					case 2:
						Utils.ExitPrgress(getActivity());
						try {
							clubModels.addAll(area_More_Clubs_Model.getClubs());
							clubOverviewZuixinAdapter_1.notifyDataSetChanged();
							// for (int i = 0; i < clubModels.size(); i++) {
							//    
							// + clubModels.get(i).getClub_id());
							// }
							if (judge) {
								message = new Message();
								bundle = new Bundle();
								message.what = 1;
								bundle.putString(
										"tital",
										area_More_Clubs_Model.getArea()
												.getArea_name()
												+ getResources().getString(
														R.string.l_xb50));

								message.setData(bundle);
								mHandler.sendMessage(message);
								judge = false;
							}
							mPullToRefreshView.onFooterRefreshComplete();
							mPullToRefreshView.onHeaderRefreshComplete();
							if (mPullToRefreshView.getVisibility() == 8) {
								mPullToRefreshView.setVisibility(View.VISIBLE);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}

						//    ("跟新数据");
						break;
					case 3:
						Utils.ExitPrgress(getActivity());
						try {
							Utils.showMessage(getActivity(), getResources()
									.getString(R.string.l_xa10));
							mPullToRefreshView.onFooterRefreshComplete();
							mPullToRefreshView.onHeaderRefreshComplete();
							if (mPullToRefreshView.getVisibility() == 0
									&& clubModels.isEmpty()) {
								mPullToRefreshView.setVisibility(View.GONE);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}

						break;
					case 4:
						Utils.ExitPrgress(getActivity());
						try {
//							   ("开始加载类别数据中");
							popwindows_Adapter = new Popwindows_Adapter(
									clueTypeModels, getActivity());
							type_list.setAdapter(popwindows_Adapter);
							type_list
									.setOnItemClickListener(new OnItemClickListener() {

										@Override
										public void onItemClick(
												AdapterView<?> arg0, View arg1,
												int position, long arg3) {
											tid = clueTypeModels.get(position)
													.getId();
											xgridview_TheKeyword
													.setVisibility(View.VISIBLE);
											xgridview_search
													.setVisibility(View.GONE);
											xgridview_TheKeyword
													.setText(clueTypeModels
															.get(position)
															.getName());
											isSouSuo1 = false;
											Page = 1;
											clubModels.clear();
											clubOverviewZuixinAdapter_1
													.notifyDataSetChanged();
											clubs(Page,
													areaid,
													com.badibadi.mytools.Dialog
															.getSystemLanguageType(ClubRigionListActivity.this),
													type_temp, tid);
											if (popup != null) {
												popup.dismiss();
											}
										}
									});
						} catch (Exception e) {
							// TODO: handle exception
						}

						break;
					default:
						break;
					}
				} catch (Exception e) {
					   
				}
			}
		};

		@Override
		public void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);

		}// regionhomepage_import_layout2

		@Override
		public View onCreateView(final LayoutInflater inflater,
				ViewGroup container, Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			final View view = inflater.inflate(R.layout.xgridview_club, null);
			type_temp = getArguments().getString("type");
			clubModels = new ArrayList<ClubModel>();
			clubOverviewZuixinAdapter_1 = new ClubOverviewZuixinAdapter_1(
					getActivity(), clubModels, type_temp, 0.0, 0.0);
			xgridview_keyword_kuang = (LinearLayout) view
					.findViewById(R.id.xgridview_keyword_kuang);
			xgridview_TheKeyword = (TextView) view
					.findViewById(R.id.xgridview_TheKeyword);
			xgridview_keyword_kuang.setVisibility(View.GONE);
			Page = 1;
			judge = true;
			clueTypeModels = new ArrayList<ClueTypeModel>();
			mPullToRefreshView = (PullToRefreshView) view
					.findViewById(R.id.main_pull_refresh_view_club_area);
			gv = (GridView) view.findViewById(R.id.xgridView11_club);
			// gv.setNumColumns(2);
			gv.setPadding(0, DisplayUtil.dip2px(getActivity(), 10),
					DisplayUtil.dip2px(getActivity(), 10),
					DisplayUtil.dip2px(getActivity(), 10));
			gv.setAdapter(clubOverviewZuixinAdapter_1);
			xgridview_search = (LinearLayout) view
					.findViewById(R.id.xgridview_search);
			fragment_club_overview0_btn_type_xgridview = (LinearLayout) view
					.findViewById(R.id.fragment_club_overview0_btn_type_xgridview);
			// index_autocomplete_txt_view_xgridview = (AutoCompleteTextView)
			// view
			// .findViewById(R.id.index_autocomplete_txt_view_xgridview);
			// xgridview_uppic_settings = (ImageView) view
			// .findViewById(R.id.xgridview_uppic_settings);
			InitPop(fragment_club_overview0_btn_type_xgridview);
			clubs(Page,
					areaid,
					com.badibadi.mytools.Dialog
							.getSystemLanguageType(ClubRigionListActivity.this),
					type_temp, tid);
			mPullToRefreshView.setOnHeaderRefreshListener(this);
			mPullToRefreshView.setOnFooterRefreshListener(this);
			// mPullToRefreshView.setEnablePullLoadMoreDataStatus(false);
			// mPullToRefreshView.setEnablePullTorefresh(true);
			return view;
		}

		private void InitPop(final View v) {
			fragment_club_overview0_btn_type_xgridview
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
//							   ("点击成功");
							OpenOrClosePopWindows(v);
						}
					});
		}

		/**
		 * 打开或管理悬浮对话框
		 * 
		 * @param inflater
		 * @param v
		 */
		public void OpenOrClosePopWindows(View v) {

			LayoutInflater inflater = LayoutInflater.from(getActivity());
			View root = inflater.inflate(
					R.layout.fragment_club_overview_popwindows, null);
			type_list = (ListView) root.findViewById(R.id.type_list);
			popup = new PopupWindow(root,
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT);
			popup.setBackgroundDrawable(new BitmapDrawable());
			popup.setFocusable(true);
			popup.setTouchable(true);
			popup.setOutsideTouchable(true);
			Ahow_Type_Clue();
			popup.showAsDropDown(v);
		}

		private void clubs(final int page, final String areaid,
				final String languageType, final String type,
				final String clubType) {
			// Utils.showPrgress(getActivity());
			MyThreadTool.fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					String content = Utils
							.getRequest(com.badibadi.mytools.Constants.BadiUrl_1
									+ "area/clubs?areaId="
									+ areaid
									+ "&languageType="
									+ languageType
									+ "&type="
									+ type
									+ "&page="
									+ page
									+ "&showNum=6&clubType="
									+ clubType
									+ "&uid="
									+ Utils.getUid(ClubRigionListActivity.this));
					//    
					// + "area/clubs?areaId=" + areaid + "&languageType="
					// + languageType + "&type=" + type + "&page=" + page
					// + "&showNum=6&clubType=" + clubType + "&uid="
					// + Utils.getUid(ClubRigionListActivity.this));
					if (content != null) {
						Results results = Utils.checkResult_NNN(getActivity(),
								content);
						System.out.println("shibu"+content);
						//    
						if (results != null
								&& !results.getRetmsg().equals("null")
								&& results.isRet()) {
							try {
								area_More_Clubs_Model = new Area_More_Clubs_Model();
//								   ("地区俱乐部返回结果是:"
//										+ results.getRetmsg());
								area_More_Clubs_Model = JsonUtil
										.getEntityByJsonString(
												results.getRetmsg(),
												Area_More_Clubs_Model.class);
								handler.sendEmptyMessage(2);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								   
							}
						} else {
							if (Page > 1) {
								--Page;
							} else {
								Page = 1;
							}
							handler.sendEmptyMessage(3);
						}
					} else {
						if (Page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						handler.sendEmptyMessage(1);
					}
				}
			});
		}

		private void Ahow_Type_Clue() {
			Utils.showPrgress(ClubRigionListActivity.this);
			MyThreadTool.fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					if (clueTypeModels != null) {
						clueTypeModels.clear();
					}
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("languageType", Dialog
							.getSystemLanguageType(ClubRigionListActivity.this));
					System.out.println(Dialog
							.getSystemLanguageType(ClubRigionListActivity.this));
					String cluecontent = Utils.sendRequest(map,
							Constants.BadiUrl + "show_type_clue");
					System.out.println("diqujulebu"+cluecontent);
					if (cluecontent != null) {
						Results results = Utils.checkResult_NNN(
								ClubRigionListActivity.this, cluecontent);
						if (results != null && results.getRetmsg() != null) {
							try {
//								   ("类别返回的数据:"
//										+ results.getRetmsg());
								clueTypeModels = JSONUtils.getListByJsonString(
										results.getRetmsg(),
										ClueTypeModel.class);
								
								handler.sendEmptyMessage(4);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								   
							}
						} else {
							handler.sendEmptyMessage(3);
						}
					} else {
						handler.sendEmptyMessage(1);
					}
				}
			});
		}

		@Override
		public void onFooterRefresh(PullToRefreshView view) {
			// TODO Auto-generated method stub
			clubs(++Page,
					areaid,
					com.badibadi.mytools.Dialog
							.getSystemLanguageType(ClubRigionListActivity.this),
					type_temp, tid);
		}

		@Override
		public void onHeaderRefresh(PullToRefreshView view) {
			Page = 1;
			if (clubModels != null) {
				clubModels.clear();
			}
			clubs(Page,
					areaid,
					com.badibadi.mytools.Dialog
							.getSystemLanguageType(ClubRigionListActivity.this),
					type_temp, tid);
		}

		public void Set() {
			if (xgridview_search.getVisibility() == 8) {// 隐藏
				//    ("隐藏状态，变为显示");
				// searchName = null;
				xgridview_search.setVisibility(View.VISIBLE);
				xgridview_TheKeyword.setVisibility(View.GONE);
				Page = 1;
				tid = "0";
				clubModels.clear();
				clubOverviewZuixinAdapter_1.notifyDataSetChanged();
				clubs(Page,
						areaid,
						com.badibadi.mytools.Dialog
								.getSystemLanguageType(ClubRigionListActivity.this),
						type_temp, tid);
			} else {
				((getActivity())).finish();
				getActivity().overridePendingTransition(R.anim.slide_left2,
						R.anim.slide_right2);
			}
		}
	}
}
